<template>
  <div class="dashboard-container">
    <div class="header">
      <h1>{{ getDashboardTitle }}</h1>
      <div class="user-actions">
        <span class="welcome-text">Welcome back, {{ userStore.user.username }}</span>
        <el-button type="danger" @click="handleLogout">Logout</el-button>
      </div>
    </div>

    <el-row :gutter="20">
      <!-- User Statistics Card - Only visible to administrators -->
      <el-col :span="24" v-if="userStore.isAdmin">
        <el-card class="stat-card">
          <template #header>
            <div class="card-header">
              <h3>User Statistics</h3>
            </div>
          </template>
          <div class="stat-content">
            <el-row>
              <el-col :span="12">
                <div class="stat-item">
                  <div class="stat-value primary">{{ stats?.totalUsers || 0 }}</div>
                  <div class="stat-label">Total Users</div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="stat-item">
                  <div class="stat-value success">{{ adminCount }}</div>
                  <div class="stat-label">Administrators</div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>

      <!-- Student Information Card - Only visible to regular students -->
      <el-col :span="24" v-if="userStore.isStudent">
        <el-card class="student-card">
          <template #header>
            <div class="card-header">
              <h3>Personal Learning Overview</h3>
            </div>
          </template>
          <div class="student-info">
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="info-card">
                  <div class="info-icon">
                    <el-icon><Calendar /></el-icon>
                  </div>
                  <div class="info-content">
                    <div class="info-value">{{ studentStats.totalTasks }}</div>
                    <div class="info-label">Total Projects</div>
                  </div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="info-card">
                  <div class="info-icon">
                    <el-icon><Document /></el-icon>
                  </div>
                  <div class="info-content">
                    <div class="info-value">{{ studentStats.completedTasks }}</div>
                    <div class="info-label">Completed Projects</div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- User Details Table - Only visible to administrators -->
    <el-row style="margin-top: 20px" v-if="userStore.isAdmin">
      <el-col :span="24">
        <el-card class="user-list-card">
          <template #header>
            <div class="card-header">
              <h3>User Details</h3>
            </div>
          </template>
          <el-table :data="stats?.userList || []" style="width: 100%" border stripe>
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="username" label="Username" width="180" />
            <el-table-column label="Role" width="180">
              <template #default="scope">
                <el-tag
                  v-for="role in scope.row.roles"
                  :key="role"
                  :type="role === 'ADMIN' ? 'danger' : role === 'SUPERVISOR' ? 'warning' : 'success'"
                  style="margin-right: 5px"
                >
                  {{ role === 'USER' ? 'STUDENT' : role }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="Creation Time" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- Student Task Overview - Only visible to students -->
    <el-row style="margin-top: 20px" v-if="userStore.isStudent">
      <el-col :span="24">
        <el-card class="task-card">
          <template #header>
            <div class="card-header">
              <h3>My Projects</h3>
              <el-button type="primary" size="small" @click="$router.push('/project-view')">View All Projects</el-button>
            </div>
          </template>
          <div class="task-list" v-loading="projectsLoading">
            <div v-if="myProjects.length === 0" class="empty-tasks">
              <el-empty description="No projects assigned to you" :image-size="80">
                <template #description>
                  <p>No projects assigned to you yet</p>
                  <p class="sub-text">Projects will be assigned by supervisors, please be patient</p>
                </template>
              </el-empty>
            </div>
            <div v-else>
              <div v-for="(project, index) in myProjects" :key="index" class="task-item">
                <div class="task-header">
                  <h4>{{ project.title }}</h4>
                  <el-tag :type="getStatusType(project.status)" size="small">{{ project.status }}</el-tag>
                </div>
                <div class="task-info">
                  <span class="task-supervisor">Supervisor: {{ project.supervisorName || 'Not Assigned' }}</span>
                  <span class="task-priority" v-if="project.category">
                    Category: 
                    <el-tag type="info" size="small">{{ project.category }}</el-tag>
                  </span>
                </div>
                <div class="task-time">
                  <span v-if="project.endTime">Deadline: {{ project.endTime }}</span>
                </div>
                <div class="task-actions">
                  <el-button type="primary" size="small" @click="$router.push('/project-view')">View Details</el-button>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- Role Distribution Chart -->
    <el-row style="margin-top: 20px" v-if="userStore.isAdmin && hasRoleDistribution">
      <el-col :span="24">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <h3>Role Distribution</h3>
            </div>
          </template>
          <v-chart class="chart" :option="chartOption" autoresize />
        </el-card>
      </el-col>
    </el-row>

    <!-- Admin Entry -->
    <div class="admin-actions" v-if="userStore.isAdmin">
      <el-button type="primary" @click="$router.push('/admin/users')">Enter Admin Panel</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDashboardStats, type DashboardStats } from '../api/dashboard'
import VChart from 'vue-echarts'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart } from 'echarts/charts'
import { LegendComponent, TooltipComponent, TitleComponent } from 'echarts/components'
import { 
  Calendar, 
  Document
} from '@element-plus/icons-vue'
import { getStudentProjects } from '../api/project'

// Register ECharts components
use([
  CanvasRenderer,
  PieChart,
  LegendComponent,
  TooltipComponent,
  TitleComponent
])

const router = useRouter()
const userStore = useUserStore()
const stats = ref<DashboardStats>()

// Student statistics data
const studentStats = ref({
  totalTasks: 0,
  completedTasks: 0
})

// Student project data
const myProjects = ref([])
const projectsLoading = ref(false)

// Get dashboard title based on user role
const getDashboardTitle = computed(() => {
  if (userStore.isAdmin) {
    return 'System Dashboard'
  } else if (userStore.isSupervisor) {
    return 'Supervisor Workbench'
  } else {
    return 'Learning Workbench'
  }
})

// Fetch dashboard data
const fetchDashboardData = async () => {
  try {
    stats.value = await getDashboardStats()
  } catch (error: any) {
    console.error('Failed to get dashboard data:', error)
    if (error.response?.status === 403) {
      ElMessage.error('No permission to access this data')
    } else if (error.response?.status === 401) {
      ElMessage.error('Login expired, please login again')
      userStore.handleAuthError()
    } else {
      ElMessage.error(error.response?.data?.message || 'Failed to get dashboard data')
    }
  }
}

// Fetch student project data
const fetchMyProjects = async () => {
  if (userStore.isStudent) {
    projectsLoading.value = true
    try {
      const projects = await getStudentProjects()
      myProjects.value = projects.slice(0, 3) // Only display first 3 projects
      updateProjectStats(projects) // Update project statistics
    } catch (error) {
      console.error('Failed to get project data:', error)
    } finally {
      projectsLoading.value = false
    }
  }
}

// Update project statistics
const updateProjectStats = (projects: any[]) => {
  if (projects && projects.length > 0) {
    studentStats.value.totalTasks = projects.length
    studentStats.value.completedTasks = projects.filter(project => project.status === 'Completed').length
  } else {
    // If no project data, set to 0
    studentStats.value.totalTasks = 0
    studentStats.value.completedTasks = 0
  }
}

// Chart configuration
const chartOption = computed(() => ({
  tooltip: {
    trigger: 'item',
    formatter: '{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    formatter: function(name) {
      // Display USER role as STUDENT
      return name === 'USER' ? 'STUDENT' : name;
    }
  },
  series: [
    {
      type: 'pie',
      radius: '50%',
      data: Object.entries(stats.value?.roleDistribution || {}).map(([name, value]) => ({
        // Display USER role as STUDENT
        name: name === 'USER' ? 'STUDENT' : name,
        value
      })),
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
}))

const hasRoleDistribution = computed(() => {
  return stats.value?.roleDistribution && Object.keys(stats.value.roleDistribution).length > 0
})

const adminCount = computed(() => {
  return stats.value?.userList?.filter(user => user.roles.includes('ADMIN')).length || 0
})

// Status style
const getStatusType = (status: string): 'primary' | 'success' | 'warning' | 'danger' | 'info' => {
  switch (status) {
    case 'Not Started': return 'primary'
    case 'In Progress': return 'warning'
    case 'Completed': return 'success'
    case 'Draft': return 'primary'
    case 'Midterm': return 'warning'
    case 'Final': return 'success'
    default: return 'primary'
  }
}

// Priority style
const getPriorityType = (priority: string): 'primary' | 'success' | 'warning' | 'danger' => {
  switch (priority) {
    case 'High': return 'danger'
    case 'Medium': return 'warning'
    case 'Low': return 'success'
    default: return 'warning'
  }
}

onMounted(() => {
  fetchDashboardData()
  fetchMyProjects()
})

const handleLogout = () => {
  userStore.logout()
  ElMessage.success('Logged out successfully')
  router.push('/login')
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  height: calc(100vh - 32px);
  overflow-y: auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h1 {
  margin: 0;
}

.user-actions {
  display: flex;
  align-items: center;
  gap: 20px;
}

.welcome-text {
  font-size: 16px;
}

.stat-card {
  height: 200px;
  display: flex;
  flex-direction: column;
}

.stat-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-item {
  text-align: center;
  padding: 10px;
}

.stat-value {
  font-size: 36px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-value.primary {
  color: #409EFF;
}

.stat-value.success {
  color: #67C23A;
}

.stat-label {
  color: #666;
  font-size: 14px;
}

.chart-card, .user-list-card {
  margin-top: 20px;
}

/* Student information card styles */
.student-card {
  margin-bottom: 20px;
}

.student-info {
  padding: 10px;
}

.info-card {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.info-icon {
  font-size: 30px;
  color: #409EFF;
  margin-right: 15px;
}

.info-content {
  flex: 1;
}

.info-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.info-label {
  color: #606266;
  font-size: 14px;
}

/* Task list styles */
.task-card {
  margin-bottom: 20px;
}

.task-list {
  padding: 10px;
}

.empty-tasks {
  padding: 20px;
  text-align: center;
}

.empty-tasks .sub-text {
  font-size: 12px;
  color: #909399;
}

.task-item {
  margin-bottom: 15px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.task-header h4 {
  margin: 0;
  font-size: 16px;
}

.task-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;
  color: #606266;
}

.task-time {
  font-size: 13px;
  color: #909399;
  margin-bottom: 10px;
}

.task-actions {
  display: flex;
  justify-content: flex-end;
}

.admin-actions {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-card__body) {
  padding: 15px;
}

.chart {
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.card-actions {
  display: flex;
  gap: 8px;
}
</style> 